package com.lly.netcross.thread;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;

public class ClientThread extends Thread{
    private static Logger logger = LoggerFactory.getLogger(ClientThread.class);
    private String localIp;
    private String remoteIp;
    private int localPort;
    private int remotePort;

    public ClientThread(){

    }
    public ClientThread(String localIp,int localPort,String remoteIp,int remotePort){
        this.localIp = localIp;
        this.localPort = localPort;
        this.remoteIp = remoteIp;
        this.remotePort = remotePort;
    }
    @Override
    public void run() {
        Socket p2pSocket = new Socket();
        try {
            p2pSocket.setReuseAddress(true);
            p2pSocket.bind(new InetSocketAddress(localIp,localPort));
            if (logger.isInfoEnabled()){
                logger.info("connecting to ip:" + remoteIp + " prot:" + remoteIp);
            }
            p2pSocket.connect(new InetSocketAddress(remoteIp,remotePort));
            if (logger.isInfoEnabled()){
                logger.info("connect success!");
            }
            BufferedReader br = new BufferedReader(new InputStreamReader(p2pSocket.getInputStream()));
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(p2pSocket.getOutputStream()));
            while (true){
                bw.write("hello "+System.currentTimeMillis()+"\n");
                bw.flush();
                String message = br.readLine();
                if (logger.isInfoEnabled()){
                    logger.info(message);
                }
                bw.write(message+"\n");
                bw.flush();
                if ("exit".equals(message)){
                    break;
                }
                Thread.sleep(1000L);
            }
            br.close();
            bw.close();
            p2pSocket.close();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
